package github.javaguide;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Set;
import java.util.TreeMap;

/**
 * @Author: DRevelation
 * @Date: 2020/12/23 9:47
 */
public class ComparableDemo {
    public static void main(String[] args) {
        TreeMap<Person, String> pdata = new TreeMap<>();
        pdata.put(new Person("张三", 30), "zhangsan");
        pdata.put(new Person("李四", 20), "lisi");
        pdata.put(new Person("王五", 10), "wangwu");
        pdata.put(new Person("小红", 5), "xiaohong");
        Set<Person> keys = pdata.keySet();
        for (Person key : keys) {
            System.out.println(key.getAge() + "-" + key.getName());
        }
    }
}

@Data
@AllArgsConstructor
class Person implements Comparable<Person> {

    private String name;
    private int age;

    @Override
    public int compareTo(Person o) {
        if (this.age > o.age) {
            return 1;
        }
        if (this.age < o.age) {
            return -1;
        }
        return 0;
    }
}